let app = getApp();
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
const {
  requestDataparams
} = require('../../../utils/request.js');
var sourceType = [
  ['camera'],
  ['album'],
  ['camera', 'album']
]
var sizeType = [
  ['compressed'],
  ['original'],
  ['compressed', 'original']
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: applet_park_api_url_imgUrl,
    price: '',
    beginTime: '',
    endTime: '',
    id: '',
    openId: '',
    nickName: '',
    textVal: '',
    toktn: '',
    listData: {},
    pics: [],
    imageList: [],
    orderName: false,
    ischarge: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    var that = this;
    if (options.price) {
      var price = options.price;
    }
    if (options.beginTime) {
      var beginTime = options.beginTime.substring(0, 5);
    }
    if (options.endTime) {
      var endTime = options.endTime.substring(0, 5);
    }
    if (options.ischarge) {
      this.setData({
        ischarge: options.ischarge
      })
    }
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    if (prevPage.route == "pages/myOrderList/myOrderList") {
      this.setData({
        orderName: true
      })
    }

    var that = this;
    var id = options.id;
    that.setData({
      price: price,
      beginTime: beginTime,
      endTime: endTime,
      id: id,
    })
    that.getDate()
  },
  chooseImage_album: function (e) { //选择图片

    var that = this;
    wx.chooseImage({
      sourceType: sourceType[2],
      count: 9,
      success: function (res) {
        var imgsrc = res.tempFiles;
        var pics = that.data.pics.concat(imgsrc);
        var imageList = that.data.imageList.concat(imgsrc);
        that.setData({
          pics: pics,
          imageList: imageList
        })
      }
    })
  },
  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    var src = e.currentTarget.dataset.src;
    const images = this.data.imagepreList;

    wx.previewImage({
      current: src, //当前预览的图片
      urls: images, //所有要预览的图片
    })
  },
  delect(e) { //删除图片
    var that = this;
    var pics = that.data.pics;
    var imageList = that.data.imageList;
    var index = e.currentTarget.dataset.idx;
    pics.splice(index, 1);
    imageList.splice(index, 1);
    this.setData({
      pics: pics,
      imageList: imageList
    });
  },
  submit: function () { //提交评价
    var that = this;
    var sources = '';

  },
  getDate() {
    var that = this;
    var url = '/api/mobileTerminal/queryMobileTerminalById/' + that.data.id;
    requestDataparams(url, {}, 'POST', 'json').then(response => {
      if (response.data.code == 0) {
        if (response.data.data.beginTime) {
          response.data.data.beginTime = response.data.data.beginTime.substring(0, 10)
        }
        if (response.data.data.endTime) {
          response.data.data.endTime = response.data.data.endTime.substring(0, 10)
        }
        that.setData({
          listData: response.data.data
        })

      } else {
        wx.showToast({
          title: '失败',
          icon: 'none'
        })
      }
    })
  },
  getValue(e) {
    var that = this;
    var textVal = e.detail.value;
    that.setData({
      textVal: textVal
    })
  },
  release() {
    let that = this;
    var openId = app.globalData.openId || wx.getStorageSync("OPENID");
    var nickName = app.globalData.nickName || wx.getStorageSync("nickName");
    var token = app.globalData.TOKEN || wx.getStorageSync("TOKEN");
    var price = 0
    if (!that.data.price && typeof (that.data.price) != "undefined" && that.data.price != 0) {
      price = parseInt(that.data.price) * 100
    }
    wx.request({
      url: applet_park_api_url + '/api/unifiedOrder/createOrder',
      method: 'POST',
      header: {
        Authorization: token
      },
      data: {
        orderType: '05',
        totalMoney: price, //that.data.price
        realityMoney: price, //
        actId: that.data.id,
        openId: openId,
        nickName: nickName,
        mobileContent: that.data.textVal,
        mobileImage: that.data.mobileImage,
      },
      success(res2) {
        if (res2.data.code == 0) {
          wx.showToast({
            title: '发布成功',
            icon: 'none'
          })
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          prevPage.getLists();
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  pay(e) {
    let that = this;
    var finished = true;
    for (var pic of that.data.imageList) {
      if (!pic.picUrl) { //false
        finished = false;
        break;
      }
    }
    if (finished) {
      wx.hideLoading();
      return;
    }
    //用自执行函数,来解决循环内部的异步回调问题
    (function uploadImage(i) { //上传图片
      if (i >= that.data.imageList.length) {
        return;
      }
      // var image = that.data.imageList[i];
      if (!that.data.imageList[i].picUrl && that.data.imageList[i].path) {
        var path = that.data.imageList[i].path;
        if(!path){
          wx.showToast({
            title: '请上传图片',
            icon: 'none'
          })
        }
        wx.uploadFile({
          url: 'https://jinchengit.cn:9999/api/upload',
          filePath: path,
          name: 'files',
          success(res) {
            let response = JSON.parse(res.data);
            that.setData({
              mobileImage: response.data
            })
            //检测下其他图片有没有传完
            var allFinished = true;
            for (var pic of that.data.imageList) {
              if (!pic.picUrl) { //false
                allFinished = false;
                break;
              }
            }
            var openId = app.globalData.openId || wx.getStorageSync("OPENID");
            var nickName = app.globalData.nickName || wx.getStorageSync("nickName");
            var token = app.globalData.TOKEN || wx.getStorageSync("TOKEN");
            if (!that.data.price && typeof (that.data.price) != "undefined" && that.data.price != 0) {
              price = parseInt(that.data.price) * 100
            }
            if (that.data.textVal.length <= 0) {
              wx.showToast({
                title: '请输入内容',
              })
              return
            }
            
            wx.request({
              url: applet_park_api_url + '/api/unifiedOrder/createOrder',
              method: 'POST',
              header: {
                Authorization: token
              },
              data: {
                orderType: '05',
                totalMoney: that.data.price,
                realityMoney: that.data.price,
                actId: that.data.id,
                openId: openId,
                nickName: nickName,
                mobileContent: that.data.textVal,
                mobileImage: that.data.mobileImage,
                screenSize: that.data.listData.screenSize,
                place: that.data.listData.place,
                beginTime: that.data.listData.beginTime + ' 00:00:00',
                endTime: that.data.listData.endTime + ' 00:00:00',
              },
              success(res2) {
                console.log(123)
                if (that.data.price > 0 && res2.data.code == 0) {
                  console.log(123123)
                  wx.requestPayment({
                    timeStamp: res2.data.data.timeStamp,
                    nonceStr: res2.data.data.nonceStr,
                    package: res2.data.data.prepay_id,
                    signType: 'MD5',
                    paySign: res2.data.data.sign,
                    paySource: 1,
                    success(res) {
                      wx.showToast({
                        title: '支付成功',
                      })
                      setTimeout(function () {
                        wx.showToast({
                          title: '页面跳转中',
                        })
                        var pages = getCurrentPages();
                        var prevPage = pages[pages.length - 2]; //上一个页面
                        prevPage.getLists();
                        wx.navigateBack({
                          delta: 1
                        })

                      }, 500);
                    },
                    fail(res3) {
                      
                    }
                  })
                } else if (!res2.data.length) {
                  setTimeout(function () {
                    wx.showToast({
                      title: '页面跳转中',
                    })
                    var pages = getCurrentPages();
                    var prevPage = pages[pages.length - 2]; //上一个页面
                    prevPage.getLists();
                    wx.navigateBack({
                      delta: 1
                    })

                  }, 500);
                } else {
                  wx.showToast({
                    title: '网络异常',
                  })
                }
              },
              fail(res) {
                wx.showToast({
                  title: res.data,
                })
              }
            })
          },
          fail(res) {
            
          }
        })
      } else {
        uploadImage(i + 1);
      }
    })(0);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})